package org.nvm.cfg;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.nvm.util.NVMUtils;

public class DefaultConfiguration implements DictConfiguration {
	
	private static final String DIC_PATH_MAIN = "/org/nvm/dic/main.dic";
	private static final String DIC_PATH_QUANTIFIER = "/org/nvm/dic/quantifier.dic";
	
	private static final String CONFIGER_XML_FILE = "NVMAnalyzer.cfg.xml";
	//配置属性——扩展字典
	private static final String EXT_DICT = "ext_dict";
	//配置属性——扩展停止词典
	private static final String EXT_STOP = "ext_stopwords";
	
	private boolean useSmart = false;
	
	private static DefaultConfiguration instance = null;
	
	private Properties props;
	
	public static DictConfiguration getInstance() {
		if(instance == null) {
			instance = new DefaultConfiguration();
		}
		return instance;
	}
	
	public DefaultConfiguration() {
		props = new Properties();
		InputStream is = null;
		try {
			is = this.getClass().getResourceAsStream(CONFIGER_XML_FILE);
		} catch (Exception e) {
			System.err.println("get configer resource error : " + e.getMessage());
		}
		if(is != null) {
			try {
				
				props.loadFromXML(is);
				
			} catch (Exception e) {
				System.err.println("load configer xml error : " + e.getMessage());
			} finally {
				if(is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	@Override
	public boolean useSmart() {
		return useSmart;
	}

	@Override
	public void setUseSmart(boolean useSmart) {
		this.useSmart = useSmart;
	}

	@Override
	public String getMainDictionary() {
		return DIC_PATH_MAIN;
	}

	@Override
	public String getQuantifierDicionary() {
		return DIC_PATH_QUANTIFIER;
	}

	@Override
	public List<String> getExtDictionarys() {
		return getExtDicts(EXT_DICT);
	}

	@Override
	public List<String> getExtStopWordDictionarys() {
		return getExtDicts(EXT_STOP);
	}

	private List<String> getExtDicts(String dictName) {
		List<String> list = new ArrayList<>(2);
		String fileNames = props.getProperty(dictName);
		if(NVMUtils.isNotBlank(fileNames)) {
			String[] arrays = fileNames.split(";");
			for(String fileName : arrays) {
				if(NVMUtils.isNotBlank(fileName)) {
					list.add(fileName);
				}
			}
		}
		return list;
	}
}
